#include "stm32f10x.h"
#include "stdio.h"
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#include "lwprintf.h"
#include "lwbtn.h"
#include "stm32f10x.h"
#include "usart.h"
#include "dht11.h"
#include "SysTick.h"
#include "led.h"
#include "oled.h"
#include "bmp.h"
#include <stdbool.h>   


#include  "lwpkt.h"
#include   "lwrb.h"

#define BTN_PIN         GPIO_Pin_13
#define BTN_PORT        GPIOC
#define BTN_RCC_CLK     RCC_APB2Periph_GPIOC


#define BTN_PIND         GPIO_Pin_13
#define BTN_PORTD        GPIOD
#define BTN_RCC_CLKD     RCC_APB2Periph_GPIOD
QueueHandle_t xPrintQueue = NULL;
TaskHandle_t xTask2Handle = NULL;

float temp, humi;
uint8_t lwbtn_keys;



// 外部变量（由你提供，不能改）
extern lwpkt_t pkt;
extern lwrb_t pkt_tx_rb, pkt_rx_rb;
extern uint8_t pkt_tx_rb_data[64], pkt_rx_rb_data[64];


// DMA 接收缓冲区
#define UART_RX_DMA_BUF_LEN 128
static uint8_t uart_rx_dma_buf[UART_RX_DMA_BUF_LEN];


typedef struct {
    GPIO_TypeDef* port;
    uint16_t      pin;
    uint8_t       active_level;   /* 0：低电平视为按下  1：高电平视为按下 */
} btn_pin_cfg_t;



static btn_pin_cfg_t key1_cfg = { BTN_PORT, BTN_PIN, 0 };
static btn_pin_cfg_t key2_cfg = { BTN_PORTD, BTN_PIND, 0 };

static lwbtn_btn_t buttons[] = {
    { .arg = &key1_cfg},
			
		{.arg = &key2_cfg }
		
		
};
static uint8_t get_button_state(lwbtn_t* lw, lwbtn_btn_t* btn)
{
    btn_pin_cfg_t* cfg = (btn_pin_cfg_t*)btn->arg;

    /* 读寄存器 */
    uint8_t level = (cfg->port->IDR & cfg->pin) ? 1 : 0;

    /* 与有效电平比较 */
    return (level == cfg->active_level) ? 1 : 0;
}


static void button_event(lwbtn_t* lw, lwbtn_btn_t* btn, lwbtn_evt_t evt)
{
    (void)lw; 
	  (void)btn;
    /* 这里什么也不做，或点灯、发队列均可 */
	
	    switch (evt)
    { 
			
			   /* 按键按下事件 */
        case LWBTN_EVT_ONPRESS:   
					lwprintf_printf("KEY0 DOWN\r\n");  
				break;
				 /* 按键释放事件 */
        case LWBTN_EVT_ONRELEASE: 
					lwprintf_printf("KEY0 UP\r\n");     
				break;
				   /* 单击/双击事件 */
        case LWBTN_EVT_ONCLICK:   
					//lwprintf_printf("KEY0 CLICK\r\n");  
						if (lwbtn_click_get_count(btn) == 2) {
                lwprintf_printf("Double\r\n");
            } else {
                lwprintf_printf("click\r\n");
            }
				
				
				break;
				case LWBTN_EVT_KEEPALIVE:
						printf("long preccess \n");
				break;
        default: break;
    }
}



/*-------------- GPIO 初始化 --------------*/
static void btn_gpio_init(void)
{
    RCC_APB2PeriphClockCmd(BTN_RCC_CLK, ENABLE);
    GPIO_InitTypeDef gpio = {
        .GPIO_Pin  = BTN_PIN,
        .GPIO_Mode = GPIO_Mode_IPU   // 上拉输入
    };
    GPIO_Init(BTN_PORT, &gpio);
}



int my_uart_send_char(int ch, struct lwprintf *lwobj)
{
    while (!(USART1->SR & USART_SR_TXE))
        ; // 等待上一次发送完成
    USART1->DR = (uint8_t)ch;
    return ch;
}





void LED_GPIO_Config(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
    GPIO_Init(GPIOE, &GPIO_InitStructure);
    GPIO_SetBits(GPIOE, GPIO_Pin_7);
	
	
}

void vTask1(void *pvParameters)
{ 
	lwprintf_printf("Task1 is running\n");
    LED_GPIO_Config();
	
 

    for (;;)
    {
     	lwprintf_printf("Task1 is running\n");
			
			
			
        vTaskDelay(pdMS_TO_TICKS(1000));
      
    }
}
void vTask2(void *pvParameters)
{

  OLED_Init();
	//OLED_ColorTurn(0);//0正常显示，1 反色显示
	//OLED_ShowPicture(0,0,128,64,BMP1,1);
	//OLED_Refresh();
	
	    
    for (;;)
    {

      
			//lwprintf_printf("Task2 is running\n");
       LEDS_Runs();
				
			/* 

			if (USART1_RX_STA & 0x8000)
        {
            u16 len = USART1_RX_STA & 0x3FFF;      // 去掉标志位，得到长度
            USART1_RX_BUF[len] = 0;                // 手动补字符串结束符
            lwprintf_printf("You sent: %s\r\n", USART1_RX_BUF);   // 回发
            USART1_RX_STA = 0;                     // 清标志，准备下一次接收
        }
        
			 
			*/ 
			
        vTaskDelay(pdMS_TO_TICKS(10)); // 等待100ms
    }
}



void vTask3(void *pvParameters)
{
	
	  for (;;)
    {
			//lwprintf_printf("Task3 is running\n");
			
						if (USART1_RX_STA & 0x8000)
        {
            u16 len = USART1_RX_STA & 0x3FFF;      // 去掉标志位，得到长度
            USART1_RX_BUF[len] = 0;                // 手动补字符串结束符
            lwprintf_printf("You sent: %s\r\n", USART1_RX_BUF);   // 回发
					
					
						  if (strcmp((const char *)USART1_RX_BUF, "on") == 0)
    {
        if (xTask2Handle != NULL)
        {
            vTaskSuspend(xTask2Handle);
            lwprintf_printf("Task2 suspended\r\n");
        }
    }
    else if (strcmp((const char *)USART1_RX_BUF, "off") == 0)
    {
        if (xTask2Handle != NULL)
        {
            vTaskResume(xTask2Handle);
            lwprintf_printf("Task2 resumed\r\n");
        }
    }
						
            USART1_RX_STA = 0;                     // 清标志，准备下一次接收
        }
	  	vTaskDelay(pdMS_TO_TICKS(10)); // 等待100ms
		}
}

// 初始化定时器2
void TIM2_Init(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure;
    
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    
    // 定时器时钟频率/(预分频+1)/(重载值+1) = 中断频率
    // 假设系统时钟72MHz，预分频7199，重载值9999，则中断频率=72000000/7200/10000=1Hz
    TIM_TimeBaseStructure.TIM_Period = 9999; // 自动重装载值
    TIM_TimeBaseStructure.TIM_Prescaler = 7199; // 预分频值
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
    
    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
    
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 5; // 适当的中断优先级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    
    TIM_Cmd(TIM2, ENABLE);
}



// 定时器回调函数
void TIM2_IRQHandler(void)
{
    if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
    {
        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
     

        static uint8_t led_state = 0;
        if(led_state == 0) {
            GPIO_SetBits(GPIOE, GPIO_Pin_6); // 开灯
            led_state = 1;
					  // 2. 任务里
        } else {
            GPIO_ResetBits(GPIOE, GPIO_Pin_6); // 关灯	
            led_state = 0;
        }
				
    }
}









int main(void)
{
    SysTick_Init(72);
    USART1_Init(115200);              // 初始化串口
    lwprintf_init(my_uart_send_char); // 初始化lwprintf
    lwprintf_printf("susses\n");    // 开机打印
    LEDS_GPIO_Init(); // 初始化LED
    btn_gpio_init();
    lwbtn_init_ex(NULL, buttons, 1, get_button_state, button_event);
   
    
	   TIM2_Init();
		

	
	  xTaskCreate(vTask1, "Task1", 1024, NULL, 10, NULL); // 创建任务1
    xTaskCreate(vTask2, "Task2", 2048, NULL, 10, &xTask2Handle); // 创建任务2
	  BaseType_t ret = xTaskCreate(vTask3, "Task3", 2048, NULL, 10, NULL);
			if (ret != pdPASS) {
					lwprintf_printf("Task3 creation failed\n");
			}
    vTaskStartScheduler();
}
